<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Storetag;
use App\Models\Tag;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class TagController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function __construct()
    {
        view()->share([
            '_ygs' => 'am-in',
            '_tag' => 'am-active',
        ]);

    }
//教练标签管理首页
    public function index()
    {
        //所有标签
        $tags=Tag::all();

        return view('admin.tag.index',compact('tags'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    //新增页面
    public function create()
    {
        return view('admin.tag.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
   // 执行新增
    public function store(Storetag $request)
    {
       Tag::create($request->all());
       return redirect('/admin/tag')->with('success','新增成功');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    //编辑页面
    public function edit($id)
    {
       //当前标签
        $tag=Tag::find($id);

        return view('admin.tag.edit',compact('tag'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    //执行更新
    public function update(Request $request, $id)
    {
        //当前标签
        $tag=Tag::find($id);
            $data['name']=$request->name;
            $info=Tag::where($data)->first();
        //保证标签名唯一性
            if($request['name'] != $tag->name &&  isset($info) ){
                return back()->with('success','此标签名已被使用');
            }
            $tag->update($request->all());
            return redirect('/admin/tag');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    //删除标签
    public function destroy($id)
    {
        $info=DB::table('fixfxs_tags')->where('tag_id',$id)->first();
        if($info){
            return back()->with('success','此标签有教练在使用不能删除');
        }else{
            Tag::destroy($id);
            return back()->with('success','删除成功');
        }
    }
}
